import logging
import os
from logging.handlers import SMTPHandler, RotatingFileHandler

import babel
from flask import Flask, request
from flask_babel import Babel
from flask_bootstrap import Bootstrap
from flask_login import LoginManager
from flask_mail import Mail
from flask_migrate import Migrate
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy

from config import Config

from flask_babel import lazy_gettext as _l  # 13.2 导入替换翻译函数并重命名

app = Flask(__name__)
# 3.1, Flask configuration
app.config.from_object(Config)

# 4.3 Flask-SQLAlchemy and Flask-Migrate initialization
db = SQLAlchemy(app)
migrate = Migrate(app, db)

# 5.2 Flask-Login initialization
login = LoginManager(app)

# 5.7  the view function that handles logins
login.login_view='login'
login.login_message=_l('Please log in to access this page') # 13.2

# 10.4 先引入10.1的代码--Flask-Mail instance.
mail = Mail(app)

#
bootstrap = Bootstrap(app)

#12.3
moment = Moment(app)

babel=Babel(app)


# 7.4 log errors by email
#  1. enable the email logger when the application is running without debug mode
#  , and also when the email server exists in the configuration.
#  2. creates a SMTPHandler instance
#  3. sets its level so that it only reports errors and not warnings, informational or debugging messages
#  4. attaches it to the app.logger object from Flask.
# if not app.debug:
#     if app.config['MAIL_SERVER']:
#         auth = None
#         if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
#             auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
#         secure = None
#         if app.config['MAIL_USE_TLS']:
#             secure = ()
#         mail_handler = SMTPHandler(
#             mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
#             fromaddr='no-reply@' + app.config['MAIL_SERVER'],
#             toaddrs=app.config['ADMINS'], subject='Microblog Failure',
#             credentials=auth, secure=secure)
#         mail_handler.setLevel(logging.ERROR)
#         app.logger.addHandler(mail_handler)


# 7.5 log to a file
# 1. create log file if it doesn't already exist
# 2. limit the size of the log file to 10KB, keep the last 10 log files as backup
# 3. The logging.Formatter class provides custom formatting for the log messages.
# 4. lowering the logging level to the INFO category-- DEBUG, INFO, WARNING, ERROR and CRITICAL in increasing order of severity
if not app.debug:
    # ...

    if not os.path.exists('logs'):
        os.mkdir('logs')
    file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
                                       backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    app.logger.setLevel(logging.INFO)
    app.logger.info('Microblog startup')



# 13.1 select best language
@babel.localeselector
def get_locale():

    return request.accept_languages.best_match(app.config['LANGUAGES'])
#     return 'zh_cn'


from app import routes, models, errors